package com.team9.fitness.controller;

import com.team9.fitness.dto.SignInDTO;
import com.team9.fitness.dto.SignUpDTO;
import com.team9.fitness.service.UserService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理控制器
 * 
 * 提供用户注册、登录、查询等核心功能
 * 支持用户名唯一性检查
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    /**
     * 用户登录
     */
    @PostMapping("/signIn")
    public java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> signIn(
            @RequestBody SignInDTO signInDTO) {
        log.info("收到登录请求: username={}", signInDTO != null ? signInDTO.getUsername() : "null");

        java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> future = new java.util.concurrent.CompletableFuture<>();

        try {
            // 通过ZRDDS异步发布登录数据，让ZRDDS执行核心业务逻辑
            Map<String, Object> additionalData = new HashMap<>();
            additionalData.put("password", signInDTO.getPassword());
            additionalData.put("loginTime", java.time.LocalDateTime.now().toString());
            additionalData.put("ipAddress", "127.0.0.1"); // 实际项目中应该获取真实IP

            zrddsDataExchangeService.publishUserActionAsync("LOGIN", null, signInDTO.getUsername(),
                    additionalData, result -> {
                        // 异步回调处理结果
                        log.info("ZRDDS登录回调结果: {}", result);
                        future.complete(ResponseEntity.ok(result));
                    });

        } catch (Exception e) {
            log.error("登录处理异常", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "登录处理失败: " + e.getMessage());
            future.complete(ResponseEntity.ok(errorResponse));
        }

        return future;
    }

    /**
     * 用户注册（异步回调版本）
     */
    @PostMapping("/signUp")
    public java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> signUp(
            @RequestBody SignUpDTO signUpDTO) {
        log.info("收到注册请求: username={}", signUpDTO != null ? signUpDTO.getUsername() : "null");

        java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> future = new java.util.concurrent.CompletableFuture<>();

        try {
            // 通过ZRDDS异步发布注册数据，让ZRDDS执行核心业务逻辑
            Map<String, Object> additionalData = new HashMap<>();
            additionalData.put("password", signUpDTO.getPassword());
            additionalData.put("confirmPassword", signUpDTO.getConfirmPassword());
            additionalData.put("registerTime", java.time.LocalDateTime.now().toString());
            additionalData.put("ipAddress", "127.0.0.1"); // 实际项目中应该获取真实IP

            zrddsDataExchangeService.publishUserActionAsync("REGISTER", null, signUpDTO.getUsername(),
                    additionalData, result -> {
                        // 异步回调处理结果
                        log.info("ZRDDS注册回调结果: {}", result);
                        future.complete(ResponseEntity.ok(result));
                    });

        } catch (Exception e) {
            log.error("注册处理异常", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("message", "注册处理失败: " + e.getMessage());
            future.complete(ResponseEntity.ok(errorResponse));
        }

        return future;
    }

    /**
     * 根据用户名查找用户
     */
    @GetMapping("/{username}")
    public ResponseEntity<Map<String, Object>> getUserByUsername(@PathVariable String username) {
        log.info("查询用户: username={}", username);
        return userService.getUserByUsername(username);
    }

    /**
     * 检查用户名是否已存在
     */
    @GetMapping("/check-username/{username}")
    public ResponseEntity<Map<String, Object>> checkUsernameExists(@PathVariable String username) {
        log.info("检查用户名是否存在: username={}", username);
        return userService.getUserByUsername(username);
    }

}
